import fs from '@ohos.file.fs';

export class ImageUtil {

  static albumToCache(context: Context, arr: Array<string>): string[]|null{
    if (arr == null) {
      return null;
    }
    let caches = new Array<string>(arr.length);
    for (let i = 0;i < arr.length; i++) {
      caches[i] = ImageUtil.uriToFile(context, arr[i])!
    }
    return caches;
  }

  static uriToFile(context: Context, uriPath: string): string|null {
    let filesDir = context.filesDir;
    // file://cn.coremail.hwmail/data/storage/el2/base/haps/tablet/files/1.png
    let dir = `MailCache`
    try {
      dir = ImageUtil.mkdirRecursivelyIfNeeded(filesDir, dir);
    }
    catch (e) {
      console.log(e)
    }
    let timestamp = Date.parse(new Date().toString());
    let filePath = `${dir}/${timestamp}.png`;
    try {
      // let fileStat = await fs.stat(uriPath);
      // let buffer = new ArrayBuffer(fileStat.size > 4096 ? 4096 : fileStat.size);
      let buffer = new ArrayBuffer(4096);
      let readFile = fs.openSync(uriPath, fs.OpenMode.READ_ONLY);
      let readLen = fs.readSync(readFile.fd, buffer, { offset: 0, length: 4096 });

      let offset = 0;

      let writeFile = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      while (readLen > 0) {
        fs.writeSync(writeFile.fd, buffer);
        offset += readLen;
        readLen = fs.readSync(readFile.fd, buffer, { offset: offset, length: 4096 });
      }
      fs.closeSync(readFile);
      fs.closeSync(writeFile);
      return filePath;
    }
    catch (e) {
      console.log(e)
    }
    return null;
  }


  static mkdirRecursivelyIfNeeded(rootDir: string, newDirPath: string): string {
    let pathComponents = newDirPath.split('/');
    let dir = `${rootDir}`
    for (let i = 0;i < pathComponents.length; i++) {
      let component = pathComponents[i];
      dir += `/${component}`
      if (fs.accessSync(dir)) {
        continue
      }
      else {
        fs.mkdirSync(dir);
      }
    }
    return dir;
  }
}